// 工具类: 快速返回值
const back = require('./../utils/back');
// 数据库
const db = require('./../db/db');


// 随机小精灵的第一种方法（有问题）
const captureRandomPokemon = (pokeData) => {
    const cumulativeWeights = [];
    let totalWeight = 0;

    pokeData.forEach(pokemon => {
        totalWeight += pokemon.capture;
        cumulativeWeights.push(totalWeight);
    });

    const random = Math.random() * totalWeight;

    let left = 0, right = cumulativeWeights.length - 1;
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
        if (random > cumulativeWeights[mid]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    // console.log(pokeData[left]);
    return pokeData[left];
};

// 随机小精灵的第二种方法
const getRandomPokemon = (data) => {
    // 计算所有capture的总和  
    let totalCaptureRate = data.reduce((sum, pokemon) => sum + parseFloat(pokemon.capture), 0);

    // 生成一个随机数  
    const randomValue = Math.random() * totalCaptureRate;

    // 遍历数组，根据capture的累积值选择对象  
    let cumulativeCaptureRate = 0;
    for (let i = 0; i < data.length; i++) {
        cumulativeCaptureRate += parseFloat(data[i].capture);
        if (randomValue <= cumulativeCaptureRate) {
            return data[i]; // 返回选中的对象  
        }
    }
};
// 成功率  
const tryGetRandomValue = (successRate) => {
    const randomChance = Math.random();
    if (randomChance <= successRate) {
        return 'ok'; // 如果随机数小于或等于成功率，返回rand的值  
    } else {
        return null; // 否则返回null  
    }
};
// 随机属性用于比赛
// 随机产生属性，【属性数组，随机产生的值数量】
const getRandomUniqueElements = (arr, count) => {
    if (arr.length < count) {
        return null;
    }
    let selectedIndices = {}; // 用于跟踪已选择的索引  
    let result = []; // 存储选中的元素  
    while (result.length < count) {
        let index = Math.floor(Math.random() * arr.length); // 随机生成索引  
        if (!selectedIndices[index]) { // 检查索引是否已被选择  
            selectedIndices[index] = true; // 标记索引为已选择  
            result.push(arr[index]); // 将元素添加到结果数组中  
        }
    }
    // console.log(result);

    return result;
};

module.exports = {
    captureRandomPokemon,
    tryGetRandomValue,
    getRandomUniqueElements,
    getRandomPokemon
};